import { useEffect } from 'react'
import styles from './App.module.css'
import {
  Home,
  Login,
  Register,
  Detail,
  Search,
  ShoppingCart,
  PlaceOrderPage
} from './pages'
import { useSelector, useAppDispatch } from './redux/hook'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { getShoppingCart } from './redux/shoppingCart/slice'
const ParviteRoute = ({ children }) => {
  const jwt = useSelector((s) => s.user.jwt)
  return jwt ? children : <Navigate to="/login" />
}
function App() {
  const jwt = useSelector((s) => s.user.jwt)
  const dispatch = useAppDispatch()
  useEffect(() => {
    if (jwt) {
      dispatch(getShoppingCart(jwt))
    }
  }, [jwt, dispatch])
  return (
    <div className={styles.App}>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="login" element={<Login />} />
          <Route path="register" element={<Register />} />
          <Route path="detail/:touristId" element={<Detail />} />
          <Route path="search/:keywords?" element={<Search />} />
          <Route
            path="shoppingCart"
            element={
              <ParviteRoute>
                <ShoppingCart />
              </ParviteRoute>
            }
          />
          <Route
            path="placeOrder"
            element={
              <ParviteRoute>
                <PlaceOrderPage />
              </ParviteRoute>
            }
          />
          <Route path="*" element={<h1>404</h1>} />
        </Routes>
      </BrowserRouter>
    </div>
  )
}

export default App
